#include "ReceiveThread.h"
#include <QByteArray>
#include <QQueue>
#include <QDebug>

QQueue<QByteArray> queue_recv;

void ReceiveThread::run() {
    qDebug() << "start receiving message thread: " << QThread::currentThreadId();
    for(;;)
    {
        queue_lock.lock(); //加锁

        while(queue_recv.size() == 0)
        {
            bool f = queue_waitCond.wait(&queue_lock, 5);
			if (f == false) //timeout
			{
				QMutexLocker locker(&m_lock);
			}
        }

        readMessage(queue_recv.front());
        queue_recv.pop_front();
        queue_lock.unlock();//解锁
        queue_waitCond.wakeOne(); //唤醒添加线程
    }
}

void ReceiveThread::readMessage(const QByteArray& rawData) {
    QByteArrayList list = rawData.split(' ');
    QByteArray type = list[0], userId = list[1], data = list[2];
    if (type == "0") {
        long rtt = (timeval().tv_usec - data.toLong()) / 1000;
        emit recvPing(rtt);
    }
    if (type == "VIDEO") {
        //QByteArray compressedData = QByteArray::fromBase64(data);
        QByteArray imgData = qUncompress(rawData);
        
        QImage img;
        img.loadFromData(imgData, "JPEG");
        emit recvImg(img);
    } else if (type == "AUDIO") {
        QByteArray compressedData = QByteArray::fromBase64(data);
        QByteArray audioData = qUncompress(compressedData);

        emit recvAudio(audioData);
    } else if (type == "TEXT") {
        emit recvText(data);
    } else if (type == "CREATED") {
        emit recvCreated(data.toUInt());
    } else if (type == "JOINED") {
        QList<quint16> partnerList;
        QByteArrayList IDs = data.split(',');
        quint16 roomId = IDs[0].toUInt();
        for (int i = 1; i < IDs.size(); ++i) {
            partnerList.append(IDs[i].toUInt());
        }
        emit recvJoined(roomId, partnerList);
    } else if (type == "OTHER_JOINED") {
        emit recvNewPartner(data.toUInt());
    } else if (type == "OTHER_LEAVED") {
        emit recvLeavedPartner(data.toUInt());
    } else if (type == "DB_STATUS") {
        QByteArrayList list = userId.split(',');
        emit recvDbStatus(data, list[0].toUInt(), list[1], list[2].toUInt());
    } else if (type == "HISTORY") {
        emit recvHistoryMsg(data);
    } else if (type == "EXPERTS") {
        emit recvExpertsMsg(data);
    } else if (type == "INVITATIONS") {
        emit recvInvitationMsg(data);
    }
}
